package com.steven.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        //创建bossGroup（只负责处理连接请求） 和 workGroup（业务处理）
        //两个都是无限循环
        //这两个含有子线程的个数是系统cpu核*2
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            //创建服务器端的启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();//设置两个线程组
            bootstrap.group(bossGroup, workGroup)
                    //使用NioSocketChannel 作为服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列得到连接数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //给workergroup的eventloop的管道设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
    //                    创建通道初始化对象
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.hashCode();
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("服务器准备好");
            //绑定端口并同步
            ChannelFuture channelFuture = bootstrap.bind(6789).sync();

            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
